﻿using Core.Framework.Loger;
using Core.Framework.Model.WebSockets;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.WebSockets;
using System.Threading.Tasks;
using Core.Framework.Util;

namespace Core.Service.TaskHandle
{
    public abstract class BaseMQMsgListener
    {

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="messageQueue"></param>
        public async void SendMessage(WebSocket client, string jsonData)
        {
            // 锁
            var clientInfo = WebSocketApplication.ClientsPool[client];
            lock (clientInfo)
                clientInfo.TaskLength++;

           await WebSocketApplication.SendAsync(client, jsonData);

            MessageBackCall(clientInfo.Project?.CallUrl, jsonData);

            
        }

        /// <summary>
        /// 回调通知
        /// </summary>
        /// <returns></returns>
        public void MessageBackCall(string callUrl,string jsonData)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(callUrl) && callUrl.IndexOf("http") > -1)
                {
                    HttpClient httpClient = new HttpClient();
                    var postData = new StringContent(jsonData);
                    postData.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
                    httpClient.PostAsync(new Uri(callUrl), postData);
                }
            }
            catch (Exception e)
            {
                LogFactory.GetLogger(typeof(BaseMQMsgListener)).Debug(e);
            }
        }

        /// <summary>
        /// 构造发送参数
        /// </summary>
        /// <returns></returns>
        public virtual string StructureParameter(MessageQueue messageQueue)
        {
            return new
            {
                message = messageQueue.Message.Content,
                messageParameter = messageQueue.Message.Parameter,

                userKey = messageQueue.ClientInfo.User.Key,
                MessageKey = messageQueue.Message.MessageKey,
                userParameter = messageQueue.ClientInfo.User.Parameter,
                sendDateTime = messageQueue.Message.SendDateTime,
                template = messageQueue.Template,

                messageType = messageQueue.Message.MessageType.ToString(),
                type = "current"

            }.TryToJson();
        }
    }
}
